/*
 * tc-ir.c
 *
 * Entry point for the compiler from Turandot to the IR.
 *
 */

#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "common.h"

void print_help();
void print_usage();

extern FILE *yyin, *yyout;

char *xname;
stopwatch_t *times;

int show_times = 0;

int main(int argc, char *argv[]) {
	xname = argv[0];
	times = stopwatch_create();
	stopwatch_start(times);

	char *ofname = NULL;

	int c;	
	opterr = 0;
	while ((c = getopt(argc, argv, "Tho:")) != -1)
		switch (c) {
		case 'T':
			show_times = 1;
			break;
		case 'h':
			print_help();
			return 0;
		case 'o':
			ofname = optarg;
		case '?':
			switch (optopt) {
			case 'o':
				ferrf("-%c: argument required", optopt);
				break;
			default:
				ferrf("-%c: unknown option", optopt);
			}
		default:
			ferrf("unknown error (%s:%d)", __FILE__, __LINE__);
		}

	FILE *input=stdin, *output=stdout;

	int arg_count = argc-optind;
	if (arg_count > 1)
		ferr("too many options");
	else if (arg_count == 1) {
		input = fopen(argv[optind], "r");
		if (!input)
			ferrf("%s: error opening file", argv[optind]);
	}
	if (ofname) {
		output = fopen(ofname, "w");
		if (!output)
			ferrf("%s: error opening file", ofname);
	}

	// initialization
	init_ident();
	init_modules();

	yyin = input;
	yyout = output;
	yyparse();

	fclose(input);
	fclose(output);	

	// cleanup
	cleanup_ident();
	cleanup_modules();

	return 0;
}

void print_usage() {
	// TODO print some usage information
}

void print_help() {
	// TODO actually print some useful help
	print_usage();
}
